<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/12/23 0023
 * Time: 11:01
 */

namespace app\index\controller;


use app\BaseController;
use app\index\model\Goods;
use app\index\model\GoodsImage;
use think\Exception;
use think\facade\Db;
use think\facade\Request;
use think\facade\Filesystem;
use think\facade\View;

class Cate extends BaseController
{
    public function cate()
    {
        // 1 接参，过滤
        $data = Request::get('','','trim,htmlspecialchars,strip_tags');
        $get=Request::get('cid',0);

        // 2 调用模型类获取数据
        $list = \app\index\model\Gcategory::getGcategory($get);

        // 3 模版赋值
//        $empty = "<tr><td colspan='8' align='center'>暂时没有数据</td></tr>";
//        View::assign('empty',$empty);
        View::assign($data);
        // 3.5新增
        if(Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');

            $cateObj = new \app\index\model\Gcategory();
            $result = $cateObj->cateAdd($post);

            if($result and $post['button']=="提交并继续"){
                $this->success("成功！ID为:".$cateObj->getInsertId());
            }else if($result and $post['button']=="提交并返回"){
                $this->success("成功！ID为:".$cateObj->getInsertId(),url('cate'));
            }else{
                $this->error("失败！原因:".$cateObj->getError());
            }
        }
        //  调用模型类获取数据
        $cates = Db::name('gcategory')->select();
        // 4 模版渲染
        return View::fetch('',['list'=>$list,'cates'=>$cates]);
    }
    public function changecate()
    {
        if(Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');

            $cateObj = new \app\index\model\Gcategory();
            $result = $cateObj->changecate($post);

            if($result){
                $this->success("成功！",url('cate',Request::get()));
            }else{
                $this->error("失败！");
            }
        }else{

            //  显示修改的页面
            $id = Request::get('id','','trim,htmlspecialchars,strip_tags');
            $cateObj = \app\index\model\Gcategory::find($id);
            if (empty($cateObj)){
                $this->error('参数错误!',url('cate'));
            }
            //  调用模型类获取数据
            $cates = Db::name('gcategory')->select();
            View::assign($cateObj->toArray());
            // 渲染，传参
            return View::fetch('',['cates'=>$cates]);
        }
    }

    public function good_list()
    {
        // 1 接参，过滤
        $goods_name = Request::get('goods_name', '', 'trim,htmlspecialchars,strip_tags');
        $recommended = Request::get('recommended', '2', 'trim,htmlspecialchars,strip_tags');
        $uptime = Request::get('up_time', '', 'trim,htmlspecialchars,strip_tags');
        $downtime = Request::get('downtime', '', 'trim,htmlspecialchars,strip_tags');
        $price_min = Request::get('price_min', '', 'trim,htmlspecialchars,strip_tags');
        $price_max = Request::get('price_max', '', 'trim,htmlspecialchars,strip_tags');
        $if_show = Request::get('if_show/a', [], 'trim,htmlspecialchars,strip_tags');
        $data = [
            'goods_name' => $goods_name,
            'recommended' => $recommended,
            'up_time' => $uptime,
            'downtime' => $downtime,
            'price_min' => $price_min,
            'price_max' => $price_max,
            'if_show' => $if_show,
        ];
        $sort = Request::get('sort','', 'trim,htmlspecialchars,strip_tags');
        $get = Request::get('','', 'trim,htmlspecialchars,strip_tags');
        if ('desc' == $sort){
            View::assign('flag','↓');
            $get['sort'] = 'asc';
        }else if('asc' == $sort){
            View::assign('flag','↑');
            unset($get['sort']);
        }else{
            $get['sort'] = 'desc';
        }
        View::assign('get',$get);
        // 2 调用模型类获取数据
        $list = \app\index\model\Goods::getGoodsList($data, $data);
        // 3 模版赋值
        $empty = "<tr><td colspan='8' align='center'>暂时没有数据</td></tr>";
        View::assign('empty', $empty);
        View::assign($data);

        // 4 模版渲染
        return View::fetch('', ['list' => $list]);
    }

    public function good_add()
    {

        if(Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');
            // 文件上传
            // 单文件上传
            try{
                // 上传验证
                $image = Request::file('default_image','');
                $rule = ['default_image'=>'filesize:40960000|fileExt:jpg,png|fileMime:image/jpeg,image/png'];
                $data = ['default_image'=>$image];
                // 验证器的方法不返回参数，如果错误会抛出异常
               validate($rule)->check($data);
               // 验证通过 执行上传
                $savename = \think\facade\Filesystem::putFile('public',$image,'get_uploadfile_name');
                $post['default_image'] = str_replace('\\','/',$savename);
                //------------------------------------------------------------------------------//
                // 多图批量上传
                $images = Request::file('banner','');
                $rule = ['banner'=>'filesize:40960000|fileExt:jpg,png|fileMime:image/jpeg,image/png'];
                $banner = [];
                foreach($images as $image){
                    $data = ['banner'=>$image];
                    validate($rule)->check($data);
                    $banner[] = \think\facade\Filesystem::putFile('public',$image,'get_uploadfile_name');
                }
                //[上传验证]使用验证数据中的键名，在规则中找相同键名的对应的规则去校验上传的文件对象
                // 捕获异常的顺序千万不要颠倒，否则会出现没有上传文件就报错，导致必须上传文件的问题
                // 验证器的方法不返回参数，如果错误会抛出异常
                // 验证通过 执行上传
            }catch(\think\exception\ValidateException $e){
                $this->error($e->getMessage());
            }catch(\think\Exception $e){}

            $post['cate_id'] = $post['cid'];
            $goodObj = new \app\index\model\Goods();
            $result = $goodObj->goodAdd($post);
            if ($result){
                $fuck = [];
                foreach ($banner as $k=>$v){
                    $fuck[$k]['goods_id'] = $goodObj->getInsertId();
                    $fuck[$k]['image_url'] = $v;
                }
            }
            $goodsimage = new GoodsImage();
            if($result and $post['button']=="提交并继续"){
                $goodsimage->saveAll($fuck);
                $this->success("成功！ID为:".$goodObj->getInsertId());
            }else if($result and $post['button']=="提交并返回"){
                $goodsimage->saveAll($fuck);
                $this->success("成功！ID为:".$goodObj->getInsertId(),url('good_list'));
            }else{
                $this->error("失败！原因:".$goodObj->getError());
            }
        }else{
            //  调用模型类获取数据
            $cates = Db::name('gcategory')->select();
            $props = Db::name('brand')->select();
            // 渲染，传参
            return View::fetch('',['cates'=>$cates,'props'=>$props]);
        }
    }
    public function changegoodlist()
    {
        if(Request::isPost()){
            $post = Request::post('','','trim,htmlspecialchars,strip_tags');
            // 文件上传
            try{
                // 上传验证
                $image = Request::file('default_image','');
                $rule = ['default_image'=>'filesize:40960000|fileExt:jpg,png|fileMime:image/jpeg,image/png'];
                $data = ['default_image'=>$image];
                // 验证器的方法不返回参数，如果错误会抛出异常
                validate($rule)->check($data);
                // 验证通过 执行上传
                $savename = \think\facade\Filesystem::putFile('public',$image,'get_uploadfile_name');
                $post['default_image'] = str_replace('\\','/',$savename);
            }catch(\think\exception\ValidateException $e){
                $this->error($e->getMessage());
            }catch(\think\Exception $e){}
            //---------------------------------------------------------------------//
            $goodlistObj = new \app\index\model\Goods();
            $result = $goodlistObj->changegoodlist($post);

            if($result){
                $this->success("成功！",url('good_list',Request::get()));
            }else{
                $this->error("失败！");
            }
        }else{
            //  显示修改的页面
            $id = Request::get('id','','trim,htmlspecialchars,strip_tags');
            $goodlistObj = \app\index\model\Goods::find($id);

            if (empty($goodlistObj)){
                $this->error('参数错误!',url('good_list'));
            }
            //  调用模型类获取数据
            $cates = Db::name('gcategory')->select();
            $props = Db::name('brand')->select();
            // 渲染，传参
            View::assign($goodlistObj->toArray());
            return View::fetch('',['cates'=>$cates,'props'=>$props]);
        }
    }

    public function cate_add()
    {

    }

}